package cn.nexttec.noteplayer.viewmodels

import android.os.Message
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.nexttec.noteplayer.databases.dao.VideoFileDao
import cn.nexttec.noteplayer.injection.IoDispatcher
import cn.nexttec.noteplayer.injection.MainDispatcher
import cn.nexttec.noteplayer.models.VideoFileInfo
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class EditorViewModel @Inject constructor(
    val videoDao:VideoFileDao,
    @IoDispatcher val ioDispatcher: CoroutineDispatcher,
    @MainDispatcher val mainDispatcher: CoroutineDispatcher
):ViewModel(){

    private val _queryResult = MutableLiveData<VideoQueryResult>(VideoQueryResult.Initial)
    val queryResult get() = _queryResult
    fun loadVideo(md5: String, pos: Long) {
        viewModelScope.launch(ioDispatcher){
            val videoInfo = videoDao.getVideoByMd5(md5)
            withContext(mainDispatcher){
                if (videoInfo!= null){
                    _queryResult.value = VideoQueryResult.Success(videoInfo, pos)
                } else {
                    _queryResult.value = VideoQueryResult.Failed("对应的视频文件可能已被删除")
                }
            }
        }
    }
}

sealed class VideoQueryResult{
    object Initial:VideoQueryResult()
    data class Success(val video: VideoFileInfo,val position:Long):VideoQueryResult()
    data class Failed(val message: String):VideoQueryResult()
}